// pages/clockin/clockin.ts
import { disposeClockin,getDisposeList } from '../../../api/clockin'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: -1 as number,
    longitude: -1 as number,
    markers: [] as any,
    lat: -1,
    log: -1,
    address: '定位中...',
    isGps: false,
    id: -1,
    house: '',
    comID: -1,
    userID: -1,
    HistoryList:[],
    isSuccess:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option: any) {
    this.setData({
      lat: option.lat,
      log: option.log,
      id: option.id,
      house: option.house,
    })
    console.log(option.id, option.house)
  },
  //获取位置
  getLocation() {
    const _this = this
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      isHighAccuracy: true,
      highAccuracyExpireTime: 4000,
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const { lat, log } = _this.data
        _this.setData({
          latitude: latitude,
          longitude: longitude,
          markers: [{
            id: 1,
            latitude: res.latitude,
            longitude: res.longitude,
          }]
        })
        const distance = _this.getDistance( log,lat,res.latitude, res.longitude, )
        console.log(distance)
        if (distance < 1000) {
          _this.setData({
            isGps: true
          })
        } else {
          _this.setData({
            isGps: false
          })
        }
        console.log(res, distance, Number(lat), Number(log), longitude, latitude)

      }
    })
  },
  checkLocationAuth() {
    let that = this
    wx.getSetting({
      success: (res) => {
        let authSetting = res.authSetting
        if (authSetting['scope.userLocation']) {
          that.getLocation()
        } else if (authSetting['scope.userLocation'] === false) {
          wx.showModal({
            title: '您未开启地理位置授权',
            content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        } else {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              that.getLocation()
            },
            fail: () => {
              wx.showModal({
                title: '您未开启地理位置授权',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  reverseGeocode(latitude: number, longitude: number) {
    const apiKey = 'YvSi5eCAVD6v3Z0OUeqjdF0oYQcnK7gt'; // 替换为你的百度地图API密钥（AK）
    const apiUrl = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${apiKey}&output=json&coordtype=wgs84ll&location=${longitude},${latitude}`;
    return new Promise((resolve, reject) => {
      wx.request({
        url: apiUrl,
        success: (res: any) => {
          if (res.data.status === 0) {
            const address = res.data.result.formatted_address;
            resolve(address)
            console.log('地址：', address);
            // 在这里处理地址信息，例如更新页面上的文本或执行其他操作
          } else {
            reject(res.data.message)
            // console.error('逆地址解析失败：', res.data.message);
          }
        },
        fail: (error) => {
          console.error('请求失败：', error);
        }
      });
    })

  },
  getDistance(lat1: string, lon1: string, lat2: string, lon2: string) {
    const R = 6371e3; // 地球半径，单位：米
    const lat1Rad = lat1 * (Math.PI / 180); // 将纬度转换为弧度
    const lat2Rad = lat2 * (Math.PI / 180); // 将纬度转换为弧度
    const deltaLat = (lat2 - lat1) * (Math.PI / 180); // 计算纬度之差并转换为弧度
    const deltaLon = (lon2 - lon1) * (Math.PI / 180); // 计算经度之差并转换为弧度

    const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
      Math.cos(lat1Rad) * Math.cos(lat2Rad) *
      Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    console.log(R * c)
    return R * c; // 返回两点之间的距离（以米为单位）

  },
  onClickLeft() {
    wx.navigateBack({
      delta: 1
    })
  },
  onNoScope() {
    let _this = this
    let { isGps, id, house, latitude, longitude, userID, comID } = _this.data
    if (isGps) {
      disposeClockin('住户维修打卡记录', id, latitude, longitude, house, userID, comID).then((res: any) => {
        console.log(res)
        if (res.data.code == 200) {
          wx.showToast({
            title: '打卡成功'
          })
          this.setData({
            isSuccess:true
          })
          this.getHistoryList();
        } else {
          wx.showToast({
            title: '打卡失败',
            icon: 'error'
          })
        }
      }).catch(err => {
        wx.showToast({
          title: '打卡失败',
          icon: 'error'
        })
      })

    } else {
      wx.showModal({
        title: '错误',
        content: '不在打卡范围内',
        confirmText: '重新定位',
        success(res) {
          if (res.confirm) {
            _this.checkLocationAuth()
          } else if (res.cancel) {
          }
        }
      })
    }
  },
  getHistoryList(){
    const {userID} = this.data
    const comID = wx.getStorageSync("userInfo").data.comID
    getDisposeList(comID,userID).then((res:any)=>{
      this.setData({
        HistoryList:res.data.data
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    const { lat, log } = this.data
    this.checkLocationAuth();
    const address = await this.reverseGeocode(lat, log)
    this.setData({
      address: address,
      comID: wx.getStorageSync("userInfo").data.comID,
      userID: wx.getStorageSync("userInfo").data.userID
    })
    await this.getHistoryList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})